<template>
  <div>
    <list-page
      ref="listPage"
      :stripe='true'
      :columns='tableColumns'
      :columnKey='columnKey'
      :data='listData'
      :loading='loading'
      :totalCount='totalCount'
      :pageIndex='pageIndex'
      :autoActionColumn='false'
      @load-data='loadData'
      @show-add='showAddModel'
      @show-edit='showEditModel'
      @delete-handle='deleteActionHandle'
    >
    </list-page>

    <Modal
      :title="modalTitle"
      v-model="modalShow"
      :mask-closable="false"
      :closable="false"
      :footer-hide="true"
      scrollable
      class-name="vertical-center-modal"
      width="660"
    >
      <Form
        :ref="formRef"
        :model="formData"
        label-position="right"
        :rules="formValidateRule"
        :label-width="100"
      >
        <input
          v-model="formData.jobId"
          name="jobId"
          type="hidden"
        >
        <Row>
          <Col span="12">
            <FormItem label="任务名称" prop="jobName">
              <Input v-model="formData.jobName" name="jobName" placeholder="应用名称"/>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="任务分组" prop="jobGroup">
              <Input v-model="formData.jobGroup" name="jobGroup" placeholder="任务分组"/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="调度器" prop="scheduleName">
              <Input v-model="formData.scheduleName" name="scheduleName" placeholder="调度器"/>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="Bean名称" prop="jobProviderBeanName">
              <Input v-model="formData.jobProviderBeanName" name="jobProviderBeanName" placeholder="Bean名称"/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="计划类型" prop="jobType">
              <RadioGroup v-model="formData.jobType">
                <Radio label="0">表达式计划</Radio>
                <Radio label="1">简单计划</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="计划表达式" prop="cronExpression">
              <Input v-model="formData.cronExpression" name="cronExpression" placeholder="计划表达式"/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="重复次数" prop="repeatCount">
              <Input v-model="formData.repeatCount" name="repeatCount" placeholder="重复次数"/>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="间隔时间" prop="intervalInSeconds">
              <Input v-model="formData.intervalInSeconds" name="intervalInSeconds" placeholder="间隔时间"/>
            </FormItem>
          </Col>
        </Row>

        <FormItem label="任务参数">
          <Input v-model="formData.parameters" name="parameters" placeholder="任务参数"  type="textarea" :row="6"/>
        </FormItem>
        <FormItem label="任务描述">
          <Input v-model="formData.description" name="description" placeholder="description"/>
        </FormItem>

        <Row>
          <Col span="12">
            <FormItem label="开始时间">
            <DatePicker
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              placeholder="Select 开始时间"
              style="width: 200px"
              v-model="formData.startTime"
            ></DatePicker>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="结束时间">
            <DatePicker
              type="datetime"
              placeholder="Select 结束时间"
              style="width: 200px"
              v-model="formData.endTime"
            ></DatePicker>
            </FormItem>
          </Col>
        </Row>

        <FormItem>
          <div style="float: right;">
            <Button
              style="margin-right: 10px"
              @click="formCancelHandle"
            >取消</Button>
            <Button
              type="primary"
              @click="formSaveHandle"
            >保存</Button>
          </div>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import ListPage from '@/components/list-page'
import { mapActions } from 'vuex'
export default {
  name: 'jobView',
  components: {
    ListPage
  },
  data () {
    return {
      tableColumns: [
        {
          type: 'index',
          title: '序号',
          align: 'center',
          width: 60
        },
        {
          title: 'scheduleName',
          key: 'scheduleName',
          width: 150
        },
        {
          title: 'jobGroup-jobName',
          key: 'jobName',
          align: 'left',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  style: {
                    marginRight: '0px',
                    marginLeft: '0px'
                  }
                },
                params.row.jobGroup + '-' + params.row.jobName
              )
            ])
          }
        },
        {
          title: '类型',
          key: 'jobType',
          align: 'center',
          width: 80,
          render: (h, params) => {
            let jobTypeName = '表达式'
            if (params.row.jobType === 1 || params.row.jobType === '1') {
              jobTypeName = '简单'
            }
            return h('div', [
              h(
                'span',
                {
                  style: {
                    marginRight: '0px',
                    marginLeft: '0px'
                  }
                },
                jobTypeName
              )
            ])
          }
        },
        {
          title: '间隔时间',
          key: 'intervalInSeconds',
          align: 'center',
          width: 70
        },
        {
          title: '表达式',
          key: 'cronExpression',
          width: 120
        },
        {
          title: '重复次数',
          key: 'repeatCount',
          align: 'center',
          width: 70
        },
        {
          title: '成功/失败次数',
          key: 'successCount',
          width: 120,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  style: {
                    marginRight: '5px',
                    marginLeft: '5px',
                    color: 'green'
                  }
                },
                params.row.successCount
              ),
              '/',
              h(
                'span',
                {
                  style: {
                    marginRight: '5px',
                    marginLeft: '5px',
                    color: 'red'
                  }
                },
                params.row.failCount
              )
            ])
          }
        },
        {
          title: '状态',
          key: 'jobStatus',
          align: 'center',
          width: 80,
          render: (h, parameters) => {
            let status = parseInt(parameters.row.jobStatus)
            let jobStatusMapper = '正在运行'
            switch (status) {
              case 1:
                jobStatusMapper = '待运行'
                break
              case 2:
                jobStatusMapper = '待暂停'
                break
              case 3:
                jobStatusMapper = '待开始'
                break
              case 4:
                jobStatusMapper = '待停止'
                break
              case 5:
                jobStatusMapper = '待触发'
                break
              case 100:
                jobStatusMapper = '新创建'
                break
              case 101:
                jobStatusMapper = '运行'
                break
              case 102:
                jobStatusMapper = '暂停'
                break
              case 103:
                jobStatusMapper = '已开始'
                break
              case 104:
                jobStatusMapper = '已停止'
                break
              case 105:
                jobStatusMapper = '触发'
                break
              case 200:
                jobStatusMapper = '完成'
                break
              case 500:
                jobStatusMapper = '异常'
                break
              case 501:
                jobStatusMapper = '未知'
                break
            }
            return h('div', [
              h(
                'span',
                {
                  style: {
                    marginRight: '0px',
                    marginLeft: '0px'
                  }
                },
                jobStatusMapper
              )
            ])
          }
        }, {
          title: '操作',
          key: 'jobId',
          align: 'center',
          fixed: 'right',
          width: 200,
          render: (h, params) => {
            let status = parseInt(params.row.jobStatus)
            if (status <= 99) {
              return h('div', ['暂无操作'])
            } else if (status === 101 || status === 103) {
              // 运行，已开始
              return h('div', [
                h(
                  'Button',
                  {
                    props: {
                      type: 'default',
                      size: 'small'
                    },
                    style: {
                      marginRight: '5px'
                    },
                    on: {
                      click: () => {
                        console.log(params)
                        this.pausetAction(params)
                      }
                    }
                  },
                  '暂停'
                ),
                h(
                  'Button',
                  {
                    props: {
                      type: 'default',
                      size: 'small'
                    },
                    style: {
                      marginRight: '5px'
                    },
                    on: {
                      click: () => {
                        // console.log(params)
                        this.stopAction(params)
                      }
                    }
                  },
                  '停止'
                )
              ])
            } else if (status === 200 || status === 104) {
              // 完成，停止
              return h('div', [
                h(
                  'Button',
                  {
                    props: {
                      type: 'default',
                      size: 'small'
                    },
                    style: {
                      marginRight: '5px'
                    },
                    on: {
                      click: () => {
                        console.log(params)
                        this.restartAction(params)
                      }
                    }
                  },
                  '重启'
                ),
                h(
                  'Button',
                  {
                    props: {
                      type: 'default',
                      size: 'small'
                    },
                    style: {
                      marginRight: '5px'
                    },
                    on: {
                      click: () => {
                        console.log(params)
                        this.showEditModel(params)
                      }
                    }
                  },
                  '编辑'
                ),
                h(
                  'Button',
                  {
                    props: {
                      type: 'default',
                      size: 'small'
                    },
                    style: {
                      marginRight: '5px'
                    },
                    on: {
                      click: () => {
                        console.log(params)
                        this.deleteAction(params)
                      }
                    }
                  },
                  '删除'
                )
              ])
            } else if (status === 102) {
              // 暂停
              return h('div', [
                h(
                  'Button',
                  {
                    props: {
                      type: 'default',
                      size: 'small'
                    },
                    style: {
                      marginRight: '5px'
                    },
                    on: {
                      click: () => {
                        console.log(params)
                        this.resumetAction(params)
                      }
                    }
                  },
                  '重新开始'
                )
              ])
            }
            return h('div', [''])
          }
        }
      ],
      columnKey: 'jobId',
      listData: [],
      loading: false,
      totalCount: 100,
      pageIndex: 1,
      modalTitle: 'title',
      modalShow: false,
      formRef: 'editForm',
      formData: {},
      formValidateRule: {}
    }
  },
  methods: {
    ...mapActions('jobStore', [
      'loadList',
      'getValidateRule',
      'save',
      'delete',
      'stop',
      'restart',
      'pause',
      'resume'
    ]),
    loadData: function (pageInfo) {
      console.log('>> load-data')
      if (!pageInfo) {
        pageInfo = {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize
        }
      }
      // console.log('>>>pageInfo', pageInfo)
      this.loading = true
      this.loadList(pageInfo)
        .then(res => {
          this.totalCount = res.data.total
          let data = res.data.list.map((item, index) => {
            let itemMap = this.$contextUtils.convertObjectNumberPropertieToString(
              item
            )
            return itemMap
          })
          this.listData = data
          this.loading = false
        })
        .catch(err => {
          console.log(err)
          this.loading = false
        })
    },
    clearFormData: function () {
      this.$refs[this.formRef].resetFields()
      this.formData = {}
    },
    showAddModel () {
      this.clearFormData()
      this.formData = {
        jobName: '表达式任务测试',
        jobGroup: 'default',
        scheduleName: 'scheduler-demo2',
        jobProviderBeanName: 'sampleJobProvider',
        jobType: '0',
        cronExpression: '0/10 * * * * ?',
        repeatCount: 1,
        intervalInSeconds: 30,
        description: '表达式任务测试'
      }
      console.log('showAdd')
      this.modalTitle = '新增'
      this.modalShow = true
    },
    showEditModel (params) {
      this.clearFormData()
      this.modalTitle = '编辑'
      this.modalShow = true
      for (let prop in params.row) {
        this.formData[prop] = params.row[prop]
      }
      // let grantTypes = this.formData.authorizedGrantTypes.split(',')
      // this.formData.authorizedGrantTypes = grantTypes
    },
    stopAction (params) {
      this.$Modal.confirm({
        title: '停止任务',
        content: '确定要停止任务[' + params.row.jobGroup + '-' + params.row.jobName + ']么？',
        onOk: () => {
          this.stopActionHandle(params)
        }
      })
    },
    stopActionHandle (params) {
      console.log(params.row.jobId)
      this.stop({
        jobId: params.row.jobId
      })
        .then(res => {
          // console.log(res)
          this.$Message.info('停止任务成功')
          this.loadData()
        })
        .catch(err => {
          this.$Message.error(err)
        })
    },
    deleteAction (params) {
      this.$Modal.confirm({
        title: '删除',
        content: '确定要删除[' + params.row.jobGroup + '-' + params.row.jobName + ']么？',
        onOk: () => {
          this.deleteActionHandle(params)
        }
      })
    },
    deleteActionHandle (params) {
      console.log(params.row.jobId)
      this.delete({
        jobId: params.row.jobId
      })
        .then(res => {
          // console.log(res)
          this.$Message.info('删除成功')
          this.loadData()
        })
        .catch(err => {
          this.$Message.error(err)
        })
    },
    restartAction (params) {
      this.$Modal.confirm({
        title: '重启任务',
        content: '确定要重启任务[' + params.row.jobGroup + '-' + params.row.jobName + ']么？',
        onOk: () => {
          this.restartActionHandle(params)
        }
      })
    },
    restartActionHandle (params) {
      console.log(params.row.jobId)
      this.restart({
        jobId: params.row.jobId
      })
        .then(res => {
          // console.log(res)
          this.$Message.info('重启任务成功')
          this.loadData()
        })
        .catch(err => {
          this.$Message.error(err)
        })
    },
    pausetAction (params) {
      this.$Modal.confirm({
        title: '暂停任务',
        content: '确定要暂停任务[' + params.row.jobGroup + '-' + params.row.jobName + ']么？',
        onOk: () => {
          this.pauseActionHandle(params)
        }
      })
    },
    pauseActionHandle (params) {
      console.log(params.row.jobId)
      this.pause({
        jobId: params.row.jobId
      })
        .then(res => {
          // console.log(res)
          this.$Message.info('暂停任务成功')
          this.loadData()
        })
        .catch(err => {
          this.$Message.error(err)
        })
    },
    resumetAction (params) {
      this.$Modal.confirm({
        title: '暂停任务开始',
        content: '确定要开始暂停任务[' + params.row.jobGroup + '-' + params.row.jobName + ']么？',
        onOk: () => {
          this.resumeActionHandle(params)
        }
      })
    },
    resumeActionHandle (params) {
      console.log(params.row.jobId)
      this.resume({
        jobId: params.row.jobId
      })
        .then(res => {
          // console.log(res)
          this.$Message.info('开始暂停任务成功')
          this.loadData()
        })
        .catch(err => {
          this.$Message.error(err)
        })
    },
    formCancelHandle () {
      this.modalShow = false
    },
    formSaveHandle () {
      console.log(' >>> save ')
      let _startTime = this.$config.dateToString(this.formData.startTime)
      let _endTime = this.$config.dateToString(this.formData.endTime)
      console.log(_startTime)
      const requestData = {
        jobId: this.formData.jobId,
        jobName: this.formData.jobName,
        jobGroup: this.formData.jobGroup,
        scheduleName: this.formData.scheduleName,
        jobProviderBeanName: this.formData.jobProviderBeanName,
        jobType: this.formData.jobType,
        cronExpression: this.formData.cronExpression,
        repeatCount: this.formData.repeatCount,
        intervalInSeconds: this.formData.intervalInSeconds,
        description: this.formData.description,
        parameters: this.formData.parameters,
        startTime: _startTime,
        endTime: _endTime
      }
      console.log(requestData)
      this.$refs[this.formRef].validate(valid => {
        if (!valid) {
          this.$Message.error('输入信息不合法')
        } else {
          // requestData.authorizedGrantTypes = grantTypes

          this.save(requestData)
            .then(res => {
              this.clearFormData()
              this.modalShow = false
              this.$Message.info('保存成功')
              this.loadData()
            })
            .catch(err => {
              this.$Message.error(err)
            })
        }
      })
    }
  },
  created () {
    // 加载验证规则
    this.getValidateRule().then(val => {
      this.formValidateRule = {}
      for (let ruleColumn in val) {
        this.formValidateRule[ruleColumn] = val[ruleColumn]
      }
    })
  }
}
</script>
